window.addEventListener("DOMContentLoaded", async () => {
    await requestSettings();
});

async function saveServerSettings() {
    const { invoke } = window.__TAURI__.core;
    const alpineData = Alpine.$data(document.querySelector('[x-data]'));
    const serverAddress = alpineData.serverAddress;
    await invoke('set_setting', { key: 'server_address', value: serverAddress });
    alpineData.isServerModalOpen = false;
    await requestSettings();
}

async function saveProxySettings() {
    const { invoke } = window.__TAURI__.core;
    const alpineData = Alpine.$data(document.querySelector('[x-data]'));
    const proxy = alpineData.proxy;

    await invoke('set_setting', { key: 'proxy', value: JSON.stringify(proxy) });
    alpineData.isProxyModalOpen = false;
    await requestSettings();
}

async function openPathPicker() {
    const { open } = window.__TAURI__.dialog;
    const selectedPath = await open({
        directory: true, // 选择文件夹
        multiple: false, // 不允许多选
        title: '选择图片保存路径' // 窗口标题
    });

    // 如果用户选择了路径，则更新状态
    if (selectedPath) {
        const { invoke } = window.__TAURI__.core;
        await invoke('set_setting', { key: 'image_save_path', value: selectedPath });
        Alpine.$data(document.querySelector('[x-data]')).imageSavePath = selectedPath;
        await requestSettings();
    }
}

async function requestSettings() {
    const { invoke } = window.__TAURI__.core;

    // 获取初始设置
    const proxy = await invoke('get_setting', { key: 'proxy' });
    const imageSavePath = await invoke('get_setting', { key: 'image_save_path' });
    const concurrency = await invoke('get_setting', { key: 'concurrency' });
    const link_application = await invoke('get_setting', { key: 'link_application' });
    const serverAddress = await invoke('get_setting', { key: 'server_address' });

    // 初始化 Alpine.js 数据
    const alpineData = Alpine.$data(document.querySelector('[x-data]'));
    alpineData.imageSavePath = imageSavePath || "";
    alpineData.proxy = proxy ? JSON.parse(proxy) : { url: "", port: "", username: "", password: "" };
    alpineData.concurrency = concurrency ? parseInt(concurrency) : 5; // 默认并发数为 5
    alpineData.link_application = link_application ? parseInt(link_application) : 1000; // 默认不打开链接所在应用
    alpineData.serverAddress = serverAddress || "";
    Alpine.$data(document.querySelector('[x-data]')).selectItems = await invoke("get_base_url_command");

    // 监听 concurrency 的变化
    alpineData.$watch('concurrency', async (newValue) => {
        await invoke('set_setting', { key: 'concurrency', value: newValue.toString() });
    });

    // 监听 link_application 的变化
    alpineData.$watch('link_application', async (newValue) => {
        await invoke('set_setting', { key: 'link_application', value: newValue.toString() });
    });
}
